
<template>
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑商品' : '新增商品'" width="600px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-tree-select
          v-model="form.categoryId"
          :data="categoryTree"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          check-strictly
          placeholder="请选择商品分类"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="商品描述">
        <el-input v-model="form.description" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" prop="imageUrl">
        <el-upload
          class="product-uploader"
          action="/api/product-service/admin/upload" 
          :show-file-list="false"
          :on-success="handleImageSuccess"
          :before-upload="beforeImageUpload"
        >
          <img v-if="form.imageUrl" :src="form.imageUrl" class="product-image" />
          <el-icon v-else class="uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="所需积分" prop="point">
        <el-input-number v-model="form.point" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="form.stock" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="0" :inactive-value="1" active-text="上架" inactive-text="下架"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules, type UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { Product, Category } from '@/types'
import { createProduct, updateProduct, getCategoryTree } from '@/api/modules/product'

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive<Partial<Product>>({})
const loading = ref(false)
const categoryTree = ref<Category[]>([])

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  imageUrl: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  point: [{ required: true, message: '请输入所需积分', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
})

const emit = defineEmits(['success'])

const fetchCategories = async () => {
  try {
    categoryTree.value = await getCategoryTree()
  } catch (error) {
    ElMessage.error('获取分类失败')
    console.error(error)
  }
}

onMounted(() => {
  fetchCategories()
})

const open = (product?: Product) => {
  if (product) {
    isEdit.value = true
    // Use a deep copy to prevent modifying the original table data directly
    Object.assign(form, JSON.parse(JSON.stringify(product)))
  } else {
    isEdit.value = false
    // Reset form for new product
    Object.keys(form).forEach(key => delete form[key as keyof typeof form])
    form.status = 0 // Default to '上架'
  }
  dialogVisible.value = true
}

const handleClose = () => {
  formRef.value?.resetFields()
}

const handleImageSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // 假设后端返回的格式为 { success: true, data: { url: '...' } }
  if (response.success) {
    form.imageUrl = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

const beforeImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是 JPG 或 PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (isEdit.value) {
          await updateProduct(form.id!, form)
          ElMessage.success('更新成功')
        } else {
          await createProduct(form)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        emit('success')
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }
  })
}

defineExpose({
  open
})
</script>

<style scoped>
.product-uploader .product-image {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.product-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.product-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

